﻿// owner 蒋家伟

#pragma once

// jsdk
#include "JsonUtils.h"
#include "CommonFieldDescriptor.h"
#include "Dbg_Warn_Define.h"
#include "DataSchemaChecked.h"

namespace jsdk
{
    // 类别描述 : 普通字段描述符
    template<typename T>
    class BaseTypeFieldDescriptor : public CommonFieldDescriptor
    {
        using valueType = T;
        static_assert(jsdk::is_base_type<valueType>::value, "使用了非基础类型的描述符");
    public:
        /// \ brief 创建类别字段描述符
        /// \ in variableName   变量名称
        /// \ in offset         相对偏移
        /// \ in typeName       类别名称
        BaseTypeFieldDescriptor(const std::wstring& variableName, uint64_t offset, const std::wstring& typeName) :
            CommonFieldDescriptor(variableName, offset, typeid(valueType).hash_code(), typeName){}
    private:
        virtual bool serializeValue(JsonDocument& jsonDoc, JsonObject& jsonObject) const noexcept override
        {
            // 按照字节大小流化
            const valueType* pValue =  IClassFieldDescriptor::get<valueType>();
            DBG_WARN_AND_RETURN_FALSE_UNLESS(pValue, CommonFieldDescriptor::getErrorMsgPrefix() + L"获取存储值时发生异常", L"蒋家伟", L"2023-11-30");
            JsonUtils::insert(jsonDoc, jsonObject, s_pValue_Key, JsonUtils::getDataStream(*pValue, jsonDoc));
            return true;
        }

        virtual bool unserializeValue(const JsonObject& object) noexcept override
        {
            valueType value{};
            bool success = JsonUtils::getValueFromJsonValue(JsonUtils::getJsonValue(object, s_pValue_Key), value);
            DBG_WARN_AND_RETURN_FALSE_UNLESS(success, CommonFieldDescriptor::getErrorMsgPrefix() + L"反流失败", L"蒋家伟", L"2023-11-30");
            return IClassFieldDescriptor::set(value);
        }
    };
}
